<template>
  <base-table-layout
    title="角色管理"
    :total="total"
    :current-page="queryParams.pageNum"
    :page-size="queryParams.pageSize"
    @update:currentPage="val => queryParams.pageNum = val"
    @update:pageSize="val => queryParams.pageSize = val"
    @size-change="handleSizeChange"
    @current-change="handleCurrentChange"
  >
    <!-- 搜索区域 -->
    <template #search>
      <el-input
        v-model="queryParams.roleName"
        placeholder="角色名称"
        style="width: 200px;"
        class="filter-item"
        @keyup.enter.native="handleSearch"
      />
      <el-input
        v-model="queryParams.roleCode"
        placeholder="角色编码"
        style="width: 200px;"
        class="filter-item"
        @keyup.enter.native="handleSearch"
      />
      <el-select v-model="queryParams.status" placeholder="状态" clearable class="filter-item" style="width: 120px">
        <el-option
          v-for="dict in statusOptions"
          :key="dict.value"
          :label="dict.label"
          :value="dict.value"
        />
      </el-select>
      <el-button
        class="filter-item"
        type="primary"
        icon="el-icon-search"
        @click="handleSearch"
      >搜索</el-button>
      <el-button
        class="filter-item"
        type="info"
        icon="el-icon-refresh"
        @click="resetQuery"
      >重置</el-button>
    </template>

    <!-- 操作区域 -->
    <template #operation>
      <el-button
        type="success"
        icon="el-icon-plus"
        @click="handleAdd"
      >新增</el-button>
    </template>

    <!-- 表格区域 -->
    <template #table>
      <el-table
        v-loading="loading"
        :data="roleList"
        border
        style="width: 100%"
      >
        <el-table-column label="角色编号" prop="id" align="center" width="100" />
        <el-table-column label="角色名称" prop="roleName" align="center" />
        <el-table-column label="角色编码" prop="roleCode" align="center" />
        <el-table-column label="状态" align="center" width="100">
          <template slot-scope="scope">
            <el-tag :type="scope.row.status === 0 ? 'danger' : 'success'">
              {{ scope.row.status === 0 ? '停用' : '正常' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" align="center" prop="createTime" width="180" />
        <el-table-column label="操作" align="center" width="180">
          <template slot-scope="scope">
            <el-button size="mini" @click="handleUpdate(scope.row)">编辑</el-button>
            <el-button size="mini" type="danger" @click="handleDelete(scope.row)">停用</el-button>
          </template>
        </el-table-column>
      </el-table>
    </template>

    <!-- 弹窗区域 -->
    <template #dialogs>
      <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
        <el-form ref="form" :model="form" :rules="rules" label-width="100px">
          <el-form-item label="角色名称" prop="roleName">
            <el-input v-model="form.roleName" placeholder="请输入角色名称" />
          </el-form-item>
          <el-form-item label="角色编码" prop="roleCode">
            <el-input 
              v-model="form.roleCode" 
              placeholder="请输入角色编码"
              :disabled="form.id !== undefined"
            />
          </el-form-item>
          <el-form-item label="状态">
            <el-radio-group v-model="form.status">
              <el-radio :label="0">停用</el-radio>
              <el-radio :label="1">正常</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="描述">
            <el-input v-model="form.description" type="textarea" placeholder="请输入描述" />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </el-dialog>
    </template>
  </base-table-layout>
</template>

<script>
import request from '@/utils/request'
import BaseTableLayout from '@/components/BaseTableLayout.vue'

export default {
  name: 'RoleManager',
  components: {
    BaseTableLayout
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 总条数
      total: 0,
      // 角色表格数据
      roleList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        roleName: undefined,
        roleCode: undefined,
        status: undefined
      },
      // 表单参数
      form: {
        id: undefined,
        roleName: undefined,
        roleCode: undefined,
        status: 1,
        description: undefined
      },
      // 表单校验
      rules: {
        roleName: [
          { required: true, message: '角色名称不能为空', trigger: 'blur' }
        ],
        roleCode: [
          { required: true, message: '角色编码不能为空', trigger: 'blur' }
        ]
      },
      // 状态数据字典
      statusOptions: [
        { label: '正常', value: 1 },
        { label: '停用', value: 0 }
      ]
    }
  },
  created() {
    this.getList()
  },
  methods: {
    /** 查询角色列表 */
    async getList() {
      try {
        this.loading = true
        const response = await request.get('/roles/page', {
          params: {
            current: this.queryParams.pageNum,
            size: this.queryParams.pageSize,
            roleName: this.queryParams.roleName,
            roleCode: this.queryParams.roleCode,
            status: this.queryParams.status
          }
        })
        this.roleList = response.records
        this.total = response.total
      } catch (error) {
        console.error('获取角色列表失败:', error)
        this.$message.error('获取角色列表失败')
      } finally {
        this.loading = false
      }
    },

    /** 搜索按钮操作 */
    handleSearch() {
      this.queryParams.pageNum = 1
      this.getList()
    },

    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        roleName: undefined,
        roleCode: undefined,
        status: undefined
      }
      this.handleSearch()
    },

    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '添加角色'
    },

    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      this.form = {
        id: row.id,
        roleName: row.roleName,
        roleCode: row.roleCode,
        status: row.status,
        description: row.description
      }
      this.open = true
      this.title = '修改角色'
    },

    /** 删除按钮操作 */
    async handleDelete(row) {
      try {
        await this.$confirm('是否确认删除角色名称为"' + row.roleName + '"的数据项?', '警告', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        await request.delete(`/roles/${row.id}`)
        this.$message.success('删除成功')
        this.getList()
      } catch (error) {
        if (error !== 'cancel') {
          console.error('删除失败:', error)
          this.$message.error('删除失败')
        }
      }
    },

    /** 表单重置 */
    reset() {
      this.form = {
        id: undefined,
        roleName: undefined,
        roleCode: undefined,
        status: 1,
        description: undefined
      }
      this.$nextTick(() => {
        if (this.$refs.form) {
          this.$refs.form.resetFields()
        }
      })
    },

    /** 取消按钮 */
    cancel() {
      this.open = false
      this.reset()
    },

    /** 提交按钮 */
    async submitForm() {
      try {
        await this.$refs.form.validate()
        if (this.form.id) {
          // 修改
          await request.put('/roles', this.form)
          this.$message.success('修改成功')
        } else {
          // 新增
          await request.post('/roles', this.form)
          this.$message.success('新增成功')
        }
        this.open = false
        this.getList()
      } catch (error) {
        if (error !== false) {
          console.error('提交失败:', error)
          this.$message.error('提交失败')
        }
      }
    },

    /** 分页大小改变 */
    handleSizeChange(val) {
      this.queryParams.pageSize = val
      this.getList()
    },

    /** 分页页码改变 */
    handleCurrentChange(val) {
      this.queryParams.pageNum = val
      this.getList()
    }
  }
}
</script>

<style lang="scss" scoped>
.dialog-footer {
  text-align: right;
}
</style>
